package com.wnxy.listener;

import com.wnxy.model.Ticket;
import com.wnxy.util.BeanCopyUtil;
import io.lettuce.core.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisKeyExpiredEvent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.List;
@Slf4j
//@Component
public class RedisListener extends KeyExpirationEventMessageListener {

//    private final static Logger logger = LoggerFactory.getLogger(RedisKeyExpiredEvent.class);
    @Autowired(required = false)
    private RedisClient redisClient;
    @Autowired
    private RedisTemplate<String, Object> rt;


    public RedisListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expireKey = message.toString();
        //订单失效
        if(expireKey.startsWith("wnxy:theater:order")){
            String performId = rt.opsForValue().get("p" + expireKey).toString();//performId
            String orderId=expireKey.substring(expireKey.lastIndexOf(":")+1);
            List<Object> values = rt.opsForHash().values("wnxy:theater:ticket:"+performId);
            List<Ticket> tickets = BeanCopyUtil.copyList(values, Ticket.class);
            for (Ticket ticket : tickets) {
                if(ticket.getTicketOrderId().equals(orderId)){
                    ticket.setTicketOrderId(null);
                    ticket.setTicketStatus(0);
                    rt.opsForHash().put("wnxy:theater:ticket:"+ticket.getTicketPerformId(),ticket.getTicketId()+"",ticket);

                }
            }
        }

    }
}
